<template>
	<a-popover>
		<template #content>
			<span v-if='isOverEntityPeriodMonth'>合同周期小于房租付的月份</span>
			<span v-if='isOverPeriodMonth'>合同周期小于付款方式月份</span>
		</template>
		<span :class='monthClass'>{{ month }}</span>
	</a-popover>
</template>
<script lang='ts' setup>
	import {computed} from 'vue'
	import dayjs from 'dayjs'

	const props = defineProps<{
		row: any
		entity: any
	}>()

	// 周期是否已经选好
	const timeSelected = computed(() => {
		const {entity} = props
		const rangeTime = [entity.beginTime, entity.endTime].filter(i => i)
		return rangeTime.length === 2
	})

	// 合同周期有多少个月
	const contractMonth = computed(() => {
		const {entity} = props
		if (!timeSelected.value) return 0
		const getDiffDays = dayjs(entity.endTime).diff(entity.beginTime, 'day')
		// 获取大致月份
		return Math.ceil(getDiffDays / 31)
	})

	// 房租付几
	const entityPeriodMonth = computed(() => {
		const {entity} = props
		return entity.periodMonth || 1
	})

	// 付款方式一般情况的月份
	const standardMonth = computed(() => {
		const {entity, row} = props
		return row.periodMonth === 100 ? entity.periodMonth : row.periodMonth
	})

	const isOverEntityPeriodMonth = computed(() => {
		const {row} = props
		if (row.periodMonth !== 100) return false
		return contractMonth.value < entityPeriodMonth.value
	})

	const isOverPeriodMonth = computed(() => {
		const {row} = props
		if (row.periodMonth === 100) return false
		return contractMonth.value < row.periodMonth
	})

	const isOver = computed(() => {
		return isOverEntityPeriodMonth.value || isOverPeriodMonth.value
	})

	const monthClass = computed(() => {
		return {
			'month-text': true,
			'month-error': isOver.value
		}
	})

	const month = computed(() => {
		const {row} = props
		// 如果还没选择周期，则按付款方式返回
		if (!timeSelected.value) return standardMonth.value
		if (row.periodMonth === 100) {
			// 随房租付款
			// 判断合同周期是否小于房租付的月份
			// 例如合同周期才6个月，但房租是付8，此时应该取6
			return isOverEntityPeriodMonth.value ? contractMonth.value : entityPeriodMonth.value
		} else {
			// 季付、半年、付年付
			// 判断合同周期是否小于 付款方式月份
			// 例如合同周期才6个月，但付款方式是年付x12，此时应该取6
			return isOverPeriodMonth.value ? contractMonth.value : row.periodMonth
		}
	})
</script>

<style scoped>
	.month-text {
		text-wrap: nowrap;
	}
	.month-error {
		color: red;
		cursor: pointer;
	}
</style>
